const canvas = document.querySelector("canvas");
const clearBtn = document.getElementById("clearButton");
clearBtn.onclick = clear;

const pageWidth = document.getElementById("gum-local").clientWidth;
const pageHeight = document.getElementById("gum-local").clientHeight;

canvas.width = pageWidth;
canvas.height = pageHeight;
const ctx = canvas.getContext("2d");

let painting = false;
let lastPoint = { x: undefined, y: undefined };

// 鼠标按下事件
canvas.onmousedown = function (e) {
  painting = true;
  const x = e.offsetX;
  const y = e.offsetY;
  lastPoint = { x, y };
  // drawCircle(x, y, 5);
};

// 鼠标移动事件
canvas.onmousemove = function (e) {
  if (painting) {
    const x = e.offsetX;
    const y = e.offsetY;
    const newPoint = { x, y };
    drawLine(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y, true);
    lastPoint = newPoint;
  }
};

// 鼠标松开事件
canvas.onmouseup = function () {
  painting = false;
};

// 划线函数
function drawLine(x1, y1, x2, y2, status) {
  console.log("status", status);
  ctx.lineWidth = 3;
  ctx.lineCap = "round";
  ctx.lineJoin = "round";
  ctx.strokeStyle = "#000";
  ctx.moveTo(x1, y1);
  ctx.lineTo(x2, y2);
  ctx.stroke();
  ctx.closePath();
  // 防止死循环
  if (status) {
    signaling.postMessage({
      type: "draw",
      data: [x1, y1, x2, y2],
      status,
    });
  }
}

// 清空画布
function clear(status = true) {
  const w = canvas.width;
  const h = canvas.height;
  canvas.width = w;
  canvas.height = h;
  // 防止死循环
  if (status) {
    signaling.postMessage({
      type: "clear",
    });
  }
}
